<?php

//include "config/dbconfig.php";
require_once "./lib/DBManager.php";
$dbmanager=new DBManager;
$mysqli = new mysqli($dbhost, $dbusername, $dbpassword, $dbscheme);
if ($mysqli->connect_errno) {
	echo "Не удалось подключиться к MySQL: " . $mysqli->connect_error;
};
if (!$mysqli->set_charset("utf8")) {
	printf("Ошибка при загрузке набора символов utf8: %s\n", $mysqli->error);
}

$action = isset($_POST["action"])?$_POST["action"]:$_GET["action"];
if ($action == "saveUnit") {
	if ($_GET["id"] != "") {
		if (!$mysqli->query("update unit set unit='" . $_GET["unit"] . "',increment=" . $_GET["increment"] . ",description='" . $_GET["description"]
										. "' where unit='" . $_GET["id"] . "'")) {
			echo "Не обновить запись: (" . $mysqli->errno . ") " . $mysqli->error;
		};
	} else {
		$res = $mysqli->query("insert into unit (unit,increment,description) values('" . $_GET["unit"] . "',"
						. $_GET["increment"] . ",'" . $_GET["description"] . "')");
	};
	$res = array('status' => "ok",
			'recordId' => $_GET["id"],
			'record' => array(
					'id' => $_GET["id"],
					'increment' => $_GET["increment"],
					'description' => $_GET["description"],
					'unit' => $_GET["unit"])
	);
	echo json_encode($res);
	return;
	//echo "{\"status\":\"ok\",id=\"" . $_GET["unit"] . "\"}";
}
if ($action == "saveProduct") {
	$res=$dbmanager->createOrUpdateProduct($_GET["id"], $_GET["unit"], $_GET["name"], $_GET["volume_increment"]);		 
	$_GET["id"] = $res["recordId"];
	echo json_encode($res);
	return;
	//echo "{\"status\":\"ok\",id=\"".$_GET["id"]."\"}";	
}
if ($action == "savePlanItem") {
	if ($_GET["id"] != "") {
		if (!$mysqli->query("update product_list_details set unit='" . $_GET["unit"] . "',product_id='" . $_GET["product_id"]
										. "',volume=" . $_GET["volume"]
										. ",comment='" . $_GET["comment"]."'"
										. " where id='" . $_GET["id"] . "'")) {
			echo "{\"status\":\"error\",\"error\": \"" . $mysqli->errno . " " . $mysqli->error . "\"}";
			return;
		};
	} else {
		$id = com_create_guid();
		$listid=$_POST["planid"];
		if (!$mysqli->query("insert into product_list_details (id,list_id,unit,comment,volume,product_id)"
						. " values('" . $id . "'"
						. ",'". $listid . "'"
						. ",'". $_GET["unit"] . "'"
						. ",'". $_GET["comment"] . "'"
						. "," . $_GET["volume"] . ""
						. ",'". $_GET["product_id"]
						. "')")) {
			echo "{\"status\":\"error\",\"error\": \"" . $mysqli->errno . " " . $mysqli->error . "\"}";
			return;
		};
		$_GET["id"] = $id;
	}
	$res = array('status' => "ok",
			'recordId' => $_GET["id"],
			'record' => array(
					'id' => $_GET["id"],
					'product' => $_GET["product"],
					'product_id' => $_GET["product_id"],
					'volume' => $_GET["volume"],
					'comment' => $_GET["comment"],
					'unit' => $_GET["unit"])
	);
	echo json_encode($res);
	return;
	//echo "{\"status\":\"ok\",id=\"".$_GET["id"]."\"}";	
}
if ($action == "searchProduct") {
	$sql = "select * from product where lower(name) like lower(concat('%',?,'%')) and active=1";
	$stmt = $mysqli->prepare($sql);
	$filter = $_GET["term"];
	$stmt->bind_param("s", $filter);
	if (!$stmt->execute()) {
		echo "Не удалось выполнить запрос 1: " . $mysqli->error;
		return;
	}
	$products = $stmt->get_result();
	$stmt->close();
	$res = array();
	while ($row = $products->fetch_assoc()) {
		$res[] = array(
				"xx"=>$filter,
				"id" => $row["id"],
				"name" => $row["name"],
				"unit" => $row["unit"],
				"volume_increment" => number_format ($row["volume_increment"],1)
		);
	}
	echo json_encode($res);
	return;
}

if ($action == "closeplan") {
	if (!$mysqli->query("update product_list_header set active=0"
										. " where id='" . $_GET["listid"] . "'")) {
			echo "{\"status\":\"error\",\"error\": \"" . $mysqli->errno . " " . $mysqli->error . "\"}";
			return;
	};
	header('Location: index.php');
}
?>